package com.yzc.result;

import lombok.Data;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Data
public class Result<T> {
    private int code;
    private String message;
    private T data;
    private final String timestamp;

    private static final DateTimeFormatter DATE_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public Result() {
        this.timestamp = LocalDateTime.now().format(DATE_FORMATTER);
    }

    // 成功响应（无数据）
    public static Result<Void> success() {
        return new Result<Void>()
                .setCode(ResultCodeEnum.SUCCESS.getCode())
                .setMessage(ResultCodeEnum.SUCCESS.getMessage());
    }

    // 成功响应（带数据）
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(ResultCodeEnum.SUCCESS.getCode());
        result.setMessage(ResultCodeEnum.SUCCESS.getMessage());
        result.setData(data);
        return result;
    }

    // 失败响应（通过枚举）
    public static <T> Result<T> fail(ResultCodeEnum codeEnum) {
        return fail(codeEnum, codeEnum.getMessage());
    }

    // 失败响应（自定义消息）
    public static <T> Result<T> fail(ResultCodeEnum codeEnum, String customMessage) {
        return new Result<T>()
                .setCode(codeEnum.getCode())
                .setMessage(StringUtils.hasText(customMessage) ?
                        customMessage : codeEnum.getMessage());
    }

    // 链式调用的 setter 方法（非 Lombok 生成）
    public Result<T> setCode(int code) {
        this.code = code;
        return this;
    }

    public Result<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public Result<T> setData(T data) {
        this.data = data;
        return this;
    }
}